#!/usr/bin/env python

# ftalat - Frequency Transition Latency Estimator
# Copyright (C) 2013 Universite de Versailles
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Script to proceed the results generated by extract.py and to generate
# the graph with GNUPlot

import sys, os
import glob

import mathutils
import cpuutils

# Usual argument checking
if len(sys.argv) != 3:
   print './extract.py input_folder output_file'
   sys.exit()
   
if not os.path.isdir(sys.argv[1]):
   print sys.argv[1] + " is not a directory"
   sys.exit()
   
if os.path.isdir(sys.argv[2]):
   print sys.argv[2] + " is a directory ! Please specify a file"
   sys.exit()
   
# Check turbo freq
turboFreq=0
try:
   turboFile = open(sys.argv[1] + "/turbo","r")
   turboFreq = int(turboFile.read().strip())
   turboFile.close()
except IOError:
   print "turbo file not found in " + sys.argv[1]
   sys.exit()
   
if os.path.exists(sys.argv[2]):
   var = raw_input(sys.argv[2] + " exists ! Do you want to overwrite it ? [Y/n] ")

   if var != "y" and var != "Y":
      print "Aborted"
      sys.exit()

# Get the files to proceed
resultsFiles = glob.glob(sys.argv[1]+"/*.csv")
sortedResultsFiles = sorted(resultsFiles)

results = {}
for f in sortedResultsFiles:
   # Extract the freq from the file name
   simplifiedName, fileExtension = os.path.splitext(os.path.basename(f))
   
   freqsString = simplifiedName.split("_")[1] # At this point we have "startFreq-targetFreq"
   freq = int(freqsString)
   
   # Read the file
   inFile = open(f)
   dataFile = inFile.readlines()
   inFile.close()
   
   medians = []
   for line in dataFile: 
      line = line.rstrip()
      if len(line) == 0:
         continue
         
      # Read values in line
      values = []
      valuesString = line.split(" ")
      for value in valuesString:
         values.append(int(value))
         
      medians.append(mathutils.median(values))
   results[freq]=medians
   
# Write data output
outFile = open(sys.argv[2],"w")
   
sortedKeys = sorted(results.keys())
size = len(sortedKeys)
if sortedKeys[size-1] == turboFreq: # Check turbo freq
   size = size-1

# The loop is as follow since we have to transpose the table for GNUPlot
i = 0
for key in sortedKeys:
   if str(key)[-4:] == "1000": # Check to avoid turbo
      continue
   
   outFile.write("{0}".format(key))
   for k in sortedKeys:
      outFile.write(" {0}".format((results[k][i]/float(sortedKeys[size-1]))*1000))
   outFile.write("\n")
   i+=1
outFile.close()

# write the gnuplot script
scriptFile = open(sys.argv[2] + ".script","w")
scriptFile.write("set title \"Frequencies transition latency estimation\"\n")

scriptFile.write("set autoscale x\n")
scriptFile.write("set autoscale y\n")

scriptFile.write("set ylabel \"Latency (micro-seconds)\"\n")

scriptFile.write("set term pdfcairo enhanced color\n")
scriptFile.write("set output \"" + sys.argv[2] + ".pdf\"\n")

scriptFile.write("set key out vert\n")
scriptFile.write("set key cent\n")
scriptFile.write("set key right\n")

scriptFile.write("set palette model HSV rgbformulae 3,2,2\n")
scriptFile.write("unset colorbox\n")

scriptFile.write("plot ")

# plot all freqs
for i in range(size):
   # scriptFile.write("\"" + sys.argv[2] + "\" using ($1/1000000):(${0} != 0 ? ((${0}/{2})*1000) : 1/0) axes x1y1 title \"{1} Ghz\" with linespoints".format(i+2,sortedKeys[i]/1000000.0,float(sortedKeys[size-1])))
   scriptFile.write("\"" + sys.argv[2] + "\" using ($1/1000000):(${0} != 0 ? ((${0})) : 1/0) axes x1y1 title \"{1} Ghz\" with linespoints palette frac {3}".format(i+2,sortedKeys[i]/1000000.0,float(sortedKeys[size-1]),(1.0/(len(sortedKeys)))*i))
   if i != size-1:
      scriptFile.write(", \\\n")

scriptFile.close()

# Finally, call gnuplot
os.system("gnuplot " + sys.argv[2] + ".script")
